package com.hkd.forum.controller;

import com.hkd.forum.common.AppResult;
import com.hkd.forum.common.ResultCode;
import com.hkd.forum.config.AppConfig;
import com.hkd.forum.exception.ApplicationException;
import com.hkd.forum.model.User;
import com.hkd.forum.service.impl.UserServiceImpl;
import com.hkd.forum.utils.MD5Util;
import com.hkd.forum.utils.StringUtil;
import com.hkd.forum.utils.UUIDUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Api(tags = "用户接口")
@Slf4j
@RestController
@RequestMapping("/user")//一级路径
public class UserController {
    @Autowired
    private UserServiceImpl userService;

    /**
     *
     * @param username 用户名
     * @param nickname 昵称
     * @param password 密码
     * @param passwordRepeat 确认密码
     * @return
     */

    @ApiOperation("用户注册")
    @PostMapping("/register")
    public AppResult register(@ApiParam("用户名") @RequestParam("username") @NonNull String username,
                              @ApiParam("昵称") @RequestParam("nickname") @NonNull String nickname,
                              @ApiParam("密码") @RequestParam("password") @NonNull String password,
                              @ApiParam("确认密码") @RequestParam("passwordRepeat") @NonNull String passwordRepeat){
        //1.非空校验

        //优化注解形式
       /* if(StringUtil.isEmpty(username ) ||
                StringUtil.isEmpty(nickname )||
                StringUtil.isEmpty(password )||
                StringUtil.isEmpty(passwordRepeat)
        ){
            //返回错误信息
            return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }*/

        //校验 密码 与 确认密码
        if(!password.equals(passwordRepeat)){
            log.warn(ResultCode.FAILED_TWO_PWD_NOT_SAME.toString());
            //返回错误信息
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME));
        }

        //准备数据
        User user = new User();
        user.setUsername(username);
        user.setNickname(nickname);

        //密码加密加盐
        String salt = UUIDUtil.UUID_32();
        String encryptPassword = MD5Util.md5Salt(password, salt);

        user.setPassword(encryptPassword);
        user.setSalt(salt);

        //调用service方法
        userService.createNormalUser(user);

        return AppResult.success();
    }

    /**
     * 用户登录
     * @param username 用户名
     * @param password 密码
     * @return 用户信息
     */
    @ApiOperation("用户登录")
    @PostMapping("/login")
    public AppResult login(HttpServletRequest request,
                           @ApiParam("用户名") @RequestParam("username") @NonNull String username,
                           @ApiParam("密码") @RequestParam("") @NonNull String password){

        //1.非空校验
        Assert.notNull(username, "username不能为null");
        Assert.notNull(password, "password不能为null");
        //2.调用userService
        User user = userService.login(username, password);
        //3.登录成功会将user存储到session中   后期修改为JWT令牌技术
        HttpSession session = request.getSession(true);
        session.setAttribute(AppConfig.USER_SESSION,user);
        //返回结果
        return AppResult.success();
    }

    @ApiOperation("获取用户信息")
    @GetMapping("/info")
    public AppResult<User> getUserInfo(HttpServletRequest request,
                                       @ApiParam("用户Id") @RequestParam(value = "id",required = false) Long id){
        User user = null;

        if(id == null){
            //Id为空从session中获取
            HttpSession session = request.getSession(false);
            /*//判断session和用户信息是否有效    拦截器校验过了
            
            if(session == null || session.getAttribute(AppConfig.USER_SESSION) == null){
                //返回禁止登录
                return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
            }*/
            //session有，从中获取
            user = (User) session.getAttribute(AppConfig.USER_SESSION);
        }else {
            //Id不为空
            user = userService.selectById(id);
        }
        //判断 user 是否为空
        if(user == null){
            return AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        return AppResult.success(user);
    }

    @ApiOperation("退出登录")
    @GetMapping("/logout")
    public AppResult logout (HttpServletRequest request){
        //获取session对象
        HttpSession session = request.getSession(false);
        if(session != null){
            //打印日志
            log.info("退出成功");
            session.invalidate();
        }
        return AppResult.success("退出成功");
    }

    @ApiOperation("修改个人信息")
    @PostMapping("/modifyInfo")
    public AppResult modifyInfo(HttpServletRequest request,
                                @ApiParam("用户名") @RequestParam(value =
                                        "username",required = false) String username,
                                @ApiParam("昵称") @RequestParam(value =
                                        "nickname",required = false) String nickname,
                                @ApiParam("性别") @RequestParam(value =
                                        "gender",required = false) Byte gender,
                                @ApiParam("邮箱") @RequestParam(value =
                                        "email",required = false) String email,
                                @ApiParam("电话号") @RequestParam(value =
                                        "phoneNum",required = false) String phoneNum,
                                @ApiParam("个⼈简介") @RequestParam(value =
                                        "remark",required = false) String remark){
        //非空校验
        if(StringUtil.isEmpty(username)
                && StringUtil.isEmpty(nickname)
                && StringUtil.isEmpty(email)
                && StringUtil.isEmpty(phoneNum)
                && StringUtil.isEmpty(remark)
                && gender == null){
            return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        //从session中获取用户信息
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);

        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setUsername(username);
        updateUser.setNickname(nickname);
        updateUser.setEmail(email);
        updateUser.setPhoneNum(phoneNum);
        updateUser.setRemark(remark);
        updateUser.setGender(gender);

        //调用service
        userService.modifyInfo(updateUser);
        //查询最新用户信息
        user = userService.selectById(user.getId());
        //更新session
        session.setAttribute(AppConfig.USER_SESSION,user);
        //返回结果
        return AppResult.success(user);

    }
    @ApiOperation("修改密码")
    @PostMapping("/modifyPwd")
    public AppResult modifyPassword (HttpServletRequest request,
                                     @ApiParam("原密码") @RequestParam("oldPassword") @NonNull String oldPassword,
                                     @ApiParam("新密码") @RequestParam("newPassword") @NonNull String newPassword,
                                     @ApiParam("确认密码") @RequestParam("passwordRepeat") @NonNull String passwordRepeat) {
        // 校验新密码和确认密码是否一致
        if(!newPassword.equals(passwordRepeat)){
            return AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }
        //获取当前登录用户信息
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);

        //调用service
        userService.modifyPassword(user.getId(), newPassword, oldPassword);
        //销毁session
        if(session != null){
            session.invalidate();
        }
        //返回结果
        return AppResult.success();
    }
}
